<template>
  <view class="container">
    <scroll-view
      scroll-x
      scroll-with-animation
      class="tab-view"
      :scroll-left="scrollLeft"
    >
      <view
        v-for="(item, index) in sources"
        :key="index"
        class="tab-bar-item"
        :class="[currentTab == index ? 'active' : '']"
        :data-current="index"
        @tap.stop="swichNav"
      >
        <text class="tab-bar-title">{{ item.name }}</text>
      </view>
    </scroll-view>
    <swiper
      class="tab-content"
      :current="currentTab"
      duration="300"
      @change="switchTab"
      :style="{ height: winHeight + 'px', paddingTop: '80rpx' }"
    >
      <swiper-item v-for="(dataList, idk) in data" :key="idk">
        <scroll-view
          scroll-y
          class="scoll-y"
          enableBackToTop="true"
          @scrolltolower="loadMore"
        >
          <!--start 内容部分可直接删除-->
          <view
            class="tui-list-cell tui-flex tui-flex-1"
            hover-class="tui-cell-hover"
            v-for="(item, index) in dataList.list"
            :key="index"
            @tap="detail(item)"
          >
            <image
              v-if="item.cover"
              mode="widthFix"
              :src="item.cover"
              style="width:150rpx;"
            />
            <view
              class="tui-flex-1 tui-flex tui-flex-column"
              style="padding-left:20rpx;"
            >
              <view class="tui-flex">
                <view
                  class="tui-flex-1"
                  style="font-weight:bold;font-size:38rpx;"
                  >{{ item.name }}</view
                >
                <tui-button
                  size="small"
                  :disabled="item.inBookshelf"
                  :type="item.inBookshelf ? 'gray' : 'warning'"
                  :loading="item.loading"
                  :stop="true"
                  @click="addSources(index)"
                  >{{ item.inBookshelf ? "已添加" : "加备用源" }}</tui-button
                >
              </view>
              <view class="tui-flex" style="font-size:28rpx;">
                <view class="tui-flex-1">
                  <tui-icon name="people" :size="28" :rpx="true" color="#6cc" />
                  {{ " " + item.author }}
                </view>
                <view style="color:#ccc;font-size:26rpx;">
                  <text v-if="item.status">{{ item.status }} |</text>
                  {{ item.category || "" }}
                </view>
              </view>
              <view
                v-if="item.latest_chapter_name"
                class="tui-flex"
                style="color:#555;font-size:26rpx;"
                >最新章节：{{ item.latest_chapter_name }}</view
              >
              <view
                v-if="item.update_time"
                class="tui-flex"
                style="color:#555;font-size:26rpx;"
                >更新时间：{{ item.update_time }}</view
              >
              <view class="story-description">{{ item.description }}</view>
            </view>
          </view>
          <tui-loadmore :visible="dataList.loading" :index="3" type="primary" />
          <tui-nomore :visible="!dataList.hasMore" />
          <!--end 内容部分可直接删除-->
        </scroll-view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script>
import tuiIcon from "@/components/icon/icon";
import tuiButton from "@/components/button/button.vue";
import tuiLoadmore from "@/components/loadmore/loadmore";
import tuiNomore from "@/components/nomore/nomore";
import { mapState, mapMutations } from "vuex";
const pageSize = 10;

export default {
  components: { tuiIcon, tuiButton, tuiLoadmore, tuiNomore },
  data() {
    return {
      currentTab: 0,
      book: {},
      sources: [],
      data: [],
      winHeight: 0,
      winWidth: 0,
      scrollLeft: 0
    };
  },
  computed: {
    ...mapState(["bookshelfs"])
  },
  onLoad(options) {
    // console.log(options);
    if (options._id) {
      const book = this.bookshelfs.find(bs => bs._id == options._id);
      if (!book) {
        this.tui.toast("参数错误");
        setTimeout(() => {
          uni.navigateBack({
            delta: 1
          });
        }, 1000);
      } else {
        this.book = book;
        this.getSources();
      }
    } else {
      this.tui.toast("参数错误");
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        });
      }, 1000);
    }
    uni.getSystemInfo({
      success: res => {
        this.winHeight = res.windowHeight - uni.upx2px(80);
        this.winWidth = res.windowWidth;
      }
    });
  },
  methods: {
    ...mapMutations(["setBookshelfs"]),
    getSources() {
      this.db
        .collection("book_sources")
        .where({
          enable: true
        })
        .orderBy("order", "asc")
        .field({
          _id: true,
          name: true,
          url: true,
          search: true,
          pageSize: true
        })
        .get()
        .then(res => {
          if (res.data && res.data.length > 0) {
            this.sources = this.handleSources(res.data);
            if (this.sources.length == 0) {
              this.tui.toast("没有可用源");
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1
                });
              }, 1000);
              return;
            }
            this.sources.forEach(s => {
              this.data.push({
                list: [],
                pageIndex: 1,
                loading: false,
                hasMore: true
              });
            });
            this.search();
          }
        })
        .catch(err => {
          this.tui.toast("没有可用源");
          setTimeout(() => {
            uni.navigateBack({
              delta: 1
            });
          }, 1000);
          return;
        });
    },
    handleSources(allSources) {
      const data = [];
      for (let item of allSources) {
        if (this.book.source_id == item._id) {
          continue;
        }
        if (
          this.book.other_sources &&
          this.book.other_sources.some(os => os.source_id == item._id)
        ) {
          continue;
        }
        data.push(item);
      }
      return data;
    },
    swichNav(e) {
      const cur = e.currentTarget.dataset.current;
      if (this.currentTab == cur) {
        return false;
      } else {
        this.currentTab = cur;
        if (
          this.data[this.currentTab].hasMore &&
          !this.data[this.currentTab].loading
        ) {
          this.search(this.currentTab);
        }
      }
    },
    switchTab(e) {
      if (!e.detail.source) {
        return;
      }
      this.currentTab = e.detail.current;
      if (
        this.data[this.currentTab].hasMore &&
        !this.data[this.currentTab].loading
      ) {
        this.search(this.currentTab);
      }
      this.$nextTick(() => this.checkCor(this.scrollLeft));
    },
    checkCor(scrollLeft) {
      //   console.log(scrollLeft);
      const query = uni.createSelectorQuery().in(this);
      query
        .select(".tab-view .tab-bar-item.active")
        .boundingClientRect(data => {
          if (data.left < 0) {
            const s = Math.ceil(Math.abs(data.left) / this.winWidth);
            const sc = scrollLeft - (s - 1) * this.winWidth - this.winWidth / 2;
            this.scrollLeft = sc < 0 ? 0 : sc;
          } else if (data.right > this.winWidth) {
            const s = Math.floor(data.right / this.winWidth);
            this.scrollLeft =
              (s - 1) * this.winWidth + scrollLeft + this.winWidth / 2;
          }
          //   console.log(data);
          //   console.log(this.winWidth);
        })
        .exec();
    },
    loadMore() {
      const current = this.currentTab;
      const { hasMore } = this.data[current];
      if (hasMore) {
        this.data[current].loading = true;
        this.data[current].pageIndex++;
        this.searchItem(this.data[current].pageIndex, this.sources[current]._id)
          .then(data => {
            data.forEach(item => {
              if (
                item.name == this.book.name &&
                item.author == this.book.author
              ) {
                this.data[current].list.push(item);
              }
            });
            // this.data[current].list.push(...data);
            if (data.length < this.sources[current].pageSize) {
              this.data[current].hasMore = false;
            }
            this.data[current].loading = false;
          })
          .catch(err => {
            console.log(err);
            this.data[current].loading = false;
          });
      }
    },
    search(
      current = this.currentTab,
      pageIndex = this.data[this.currentTab].pageIndex
    ) {
      //   console.log(this.sources, current, this.currentTab);
      if (!this.sources[current]._id) {
        this.tui.toast("没有选择源");
        return;
      }
      const value = this.book.name;
      if (!value) {
        this.tui.toast("请输入搜索内容");
      } else {
        this.data[current].loading = true;

        this.searchItem(pageIndex, this.sources[current].source_id)
          .then(data => {
            data.forEach(item => {
              // console.log(item, this.book);
              // console.log(item.name == this.book.name)
              // console.log(item.author == this.book.author)
              if (
                item.name == this.book.name &&
                item.author == this.book.author
              ) {
                this.data[current].list.push(item);
              }
            });
            // this.data[current].list.push(...data);
            if (data.length < this.sources[current].pageSize) {
              this.data[current].loading = false;
              this.data[current].hasMore = false;
            }
          })
          .catch(err => {
            const error = JSON.stringify(err);
            if (error.indexOf("exection timeout")) {
              this.tui.toast("请求超时了");
            } else {
              this.tui.toast("发生错误了");
            }
            console.log(JSON.stringify(err));
            this.data[current].loading = false;
          });
      }
    },
    // 由于小程序云开发最长20s请求超时，所以一页中的数据分多次请求
    async searchItem(
      pageIndex = 1,
      source_id = this.sources[this.currentTab]._id
    ) {
      const data = [];
      const res = await this.callFunc({
        name: "search",
        data: {
          source_id,
          value: this.book.name,
          pageIndex
        }
      });
      if (res.result && res.result.errMsg == "ok") {
        data.push(...res.result.data);
      } else {
        this.tui.toast(res.result.errMsg);
      }
      return data;
    },
    detail(book) {
      const { source_id, read_url } = book;
      uni.navigateTo({
        url:
          "/pages/detail/detail?source_id=" +
          source_id +
          "&read_url=" +
          read_url
      });
    },
    addSources(index) {
      this.$set(this.data[this.currentTab].list[index], "loading", true);
      const {
        name,
        author,
        read_url,
        cover,
        source_id,
        first_chapter_url,
        latest_chapter_url
      } = this.data[this.currentTab].list[index];
      this.callFunc({
        name: "addBookshelf",
        data: {
          name,
          author,
          cover,
          source_id,
          read_url,
          latest_chapter_url,
          url: first_chapter_url
        }
      }).then(res => {
        if (res.result.errMsg == "ok") {
          this.data[this.currentTab].list[index].inBookshelf = true;
          const bookshelfs = this.bookshelfs;
          // 添加备用源
          bookshelfs.forEach(bs => {
            if (bs._id == res.result.data._id) {
              bs.other_sources = res.result.data.other_sources;
            }
          });
          this.setBookshelfs(bookshelfs);
        } else {
          this.tui.toast(res.result.errMsg);
        }
        this.data[this.currentTab].list[index].loading = false;
      });
    }
  }
};
</script>

<style>
/*tabbar start*/
::-webkit-scrollbar {
  width: 0;
  height: 0;
  color: transparent;
}
.tab-view::before {
  content: "";
  position: absolute;
  border-bottom: 1upx solid #eaeef1;
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
  bottom: 0;
  right: 0;
  left: 0;
}
.tab-view {
  width: 100%;
  height: 80upx;
  overflow: hidden;
  box-sizing: border-box;
  position: fixed;
  top: 0;
  /* #ifdef H5 */
  top: 44px;
  /* #endif */
  left: 0;
  z-index: 99;
  background: #fff;
  white-space: nowrap;
}
.tab-bar-item {
  padding: 0;
  /* height: 100upx; */
  min-width: 80upx;
  /* line-height: 100upx; */
  margin: 0 28upx;
  display: inline-block;
  text-align: center;
  box-sizing: border-box;
}
.tab-bar-title {
  height: 60upx;
  line-height: 60upx;
  font-size: 26upx;
  color: #999;
  font-weight: 400;
}
.active {
  border-bottom: 6upx solid #6cc;
}
.active .tab-bar-title {
  color: #6cc !important;
  font-size: 30upx;
  font-weight: bold;
}
/*tabbar end*/
.scoll-y {
  height: 100%;
}
.list-view {
  margin-top: 100upx;
  width: 100%;
  background: #fff;
  box-sizing: border-box;
  padding-bottom: env(safe-area-inset-bottom);
}
.list-cell {
  padding: 30upx;
  box-sizing: border-box;
}
.cell-title-box {
  display: flex;
  justify-content: space-between;
}
.cell-title {
  font-size: 36upx;
  line-height: 56upx;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  /* padding-bottom: 30upx; */
}
.img-container {
  width: 100%;
  padding-top: 24upx;
  display: flex;
  height: 160upx;
  justify-content: space-between;
}
.cell-img {
  width: 32%;
  overflow: hidden;
  position: relative;
}
.img {
  width: 100%;
  height: 160upx;
  display: block;
  /* position: absolute;
		  left: 50%;
		  top:50%;
		  transform: translate(-50%,-50%);
		*/
  border-radius: 4upx;
}
.sub-title {
  padding-top: 24upx;
  font-size: 28upx;
  color: #bcbcbc;
  display: flex;
  align-items: center;
}
.badge {
  padding: 5upx 10upx;
  font-size: 24upx;
  border-radius: 4upx;
  margin-right: 20upx;
}
.b-red {
  background: #fcebef;
  color: #8a5966;
}
.b-blue {
  background: #ecf6fd;
  color: #4dabeb;
}
.b-orange {
  background: #fef5eb;
  color: #faa851;
}
.b-green {
  background: #e8f6e8;
  color: #44cf85;
}
.story-description {
  width: 100%;
  font-size: 30rpx;
  word-break: break-all;
  word-wrap: break-word;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  box-sizing: border-box;
  margin-top: 10rpx;
  color: #80848f;
}
.tui-list-cell {
  position: relative;
  width: 100%;
  padding: 26rpx 30rpx;
  box-sizing: border-box;
  overflow: hidden;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  align-items: center;
}
.tui-cell-hover {
  background: #f7f7f9 !important;
}
</style>
